package com.example.study.config;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

/**
 * 当Springboot以内置的tomcat启动的时候，直接采用Spring提供的ApplicationListener接口来监听项目的启动，
 * 在启动的时候获取到项目的端口号即可。当Springboot，打成War包，放到外部tomcat中部署的时候，
 * 就需要剔除内置的tomcat容器，此时Springboot的启动流程就和上面不一样，好像就不再有初始化WebServer的步骤了。
 * ————————————————
 * 版权声明：本文为CSDN博主「在线打码」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
 * 原文链接：https://blog.csdn.net/oNew_Lifeo/article/details/127276152
 */
@Configuration
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    //获取内置tomcat端口号
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    // 获取项目IP
    public String getIp() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if (this.serverPort == 0) { // 获取外置tomcat端口号
            this.serverPort = getTomcatPort();
        }
        return   address.getHostAddress() + ":" + this.serverPort;
    }

    public int getTomcatPort() {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            QueryExp protocol = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
            ObjectName name = new ObjectName("*:type=Connector,*");
            Set<ObjectName> objectNames = beanServer.queryNames(name, protocol);
            for (ObjectName objectName : objectNames) {
                String catalina = objectName.getDomain();
                if ("Catalina".equals(catalina)) {
                    return Integer.parseInt(objectName.getKeyProperty("port"));
                }
            }
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
